<script setup lang="ts">
/*global QC*/
import { useMobileCode } from '@/composables'
import { loginByQQ } from '@/services/order'
import { bindMobile } from '@/services/user'
import { useUSerStore } from '@/stores'
import type { User } from '@/types/USer' //你看这是你开始导入的哪有USer不是User吗
import { CodeRule, MobileRule } from '@/utils/rules'
import { showSuccessToast } from 'vant'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

const openId = ref('')
const isNeedBind = ref(true)
onMounted(() => {
  if (QC.Login.check()) {
    QC.Login.getMe((id: string) => {
      openId.value = id

      console.log('🚀 ~ QC.Login.getMe ~ openId.value:', openId.value)
      // QQ，登录
      loginByQQ(id)
        .then((res) => {
          // 登录成功
          console.log(res)
          loginSuccess(res)
          // isNeedBind.value = true
        })
        .catch(() => {
          // 登录失败
          console.log(1)

          isNeedBind.value = true
        })
    })
  }
})

const username = ref('')
const code = ref('')
const { sendLogin, Times, form } = useMobileCode(username, 'bindMobile')
//成功的逻辑
const store = useUSerStore()
const router = useRouter()
// const loginSuccess = (res: { data: User }) => {
//   store.SetUser(res.data)
//   //这个跳转和push的区别是不能点击返回按钮返回到上一层
//   router.replace(store.returnUrl || '/user')
//   // showSuccessToast('登录成功')
//   store.setReturnUrl('')
// }
const loginSuccess = (res: { data: User }) => {
  store.SetUser(res.data)
  router.replace('/user')
  showSuccessToast('登录成功')
}

//绑定
const bind = async () => {
  const res = await bindMobile({
    mobile: username.value,
    code: code.value,
    openId: openId.value
  })
  // console.log(res)
  //执行成功的逻辑
  loginSuccess(res)
}
</script>

<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="form" @submit="bind">
      <van-field
        name="mobile"
        placeholder="请输入手机号"
        v-model="username"
        :rules="MobileRule"
      ></van-field>
      <van-field
        name="code"
        placeholder="请输入验证码"
        v-model="code"
        :rules="CodeRule"
      >
        <template #button>
          <van-button
            size="small"
            :class="{ active: Times > 0 }"
            type="primary"
            @click="sendLogin"
            >{{ Times ? `${Times}秒后再次发送` : '发送验证码' }}</van-button
          >
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '/src/style/login.scss';
</style>
